package com.example.datagramsocket.utils

import com.google.gson.Gson
import com.tencent.mmkv.MMKV

/**
 * @author 宾有为
 * @date 2024/6/12 10:39
 * @link https://blog.csdn.net/baidu_41616022?type=blog
 * @describe：
 **/
object MMKVCache {

    @JvmStatic
    private val cache = MMKV.defaultMMKV()
    internal val gson : Gson by lazy { Gson() }

    fun putString(key: String, value: String) {
        cache.putString(key, value)
    }

    fun getString(key: String, defValue: String = ""): String {
        return cache.getString(key, defValue) ?: defValue
    }

    fun putInt(key: String, value: Int) {
        cache.putInt(key, value)
    }

    fun getInt(key: String, defValue: Int = 0): Int {
        return cache.getInt(key, defValue)
    }

    fun putBoolean(key: String, value: Boolean) {
        cache.putBoolean(key, value)
    }

    fun getBoolean(key: String, defValue: Boolean = false): Boolean {
        return cache.getBoolean(key, defValue)
    }

    fun putStringSet(key: String, value: Set<String>) {
        cache.putStringSet(key, value)
    }

    fun getStringSet(key: String, defValue: Set<String>): MutableSet<String> {
        return cache.getStringSet(key, defValue) ?: mutableSetOf()
    }

    fun <T> getObject(key: String, clazz: Class<T>): T? {
        return if (getString(key) == "") null else gson.fromJson<T>(getString(key), clazz)
    }

    fun <T> putObject(key: String, value: T) {
        putString(key, gson.toJson(value))
    }


    fun remove(key: String) {
        cache.remove(key)
    }

    fun remove() {
        cache.clearMemoryCache()
        cache.clearAll()
    }
}